#! /bin/bash

# 获取环境变量
PLAY_HOME=/opt/playground

function configureKyuubiConf()
{
 kyuubiConfUrl=$1
 masterNode=$2
 localnode=$3
 
 # 配置Kyuubi服务器地址
 sed -i "s/^#kyuubi.frontend.bind.host=localhost/kyuubi.frontend.bind.host=0.0.0.0/g" $kyuubiConfUrl
 sed -i "s/^#kyuubi.frontend.advertised.host=localhost/kyuubi.frontend.advertised.host=$localnode/g" $kyuubiConfUrl
 
 # 配置Kyuubi端口
 sed -i "s/^#kyuubi.frontend.bind.port=10009/kyuubi.frontend.bind.port=10009/g" $kyuubiConfUrl
 
 # 配置Kyuubi引擎类型
 sed -i "s/^#kyuubi.engine.type=SPARK_SQL/kyuubi.engine.type=SPARK_SQL/g" $kyuubiConfUrl
 
 # 配置Kyuubi认证类型
 sed -i "s/^#kyuubi.authentication=NONE/kyuubi.authentication=NONE/g" $kyuubiConfUrl
 
 # 配置Kyuubi会话超时
 sed -i "s/^#kyuubi.session.engine.idle.timeout=PT30M/kyuubi.session.engine.idle.timeout=PT30M/g" $kyuubiConfUrl
 
 echo "Kyuubi配置文件更新完成"
}

function installKyuubi()
{
 #1.在frames.txt中查看是否需要安装kyuubi
 kyuubiInfo=`egrep "^apache-kyuubi" $PLAY_HOME/frames.txt`

 kyuubi=`echo $kyuubiInfo | cut -d " " -f1`
 isInstall=`echo $kyuubiInfo | cut -d " " -f2`
 kyuubiNodes=`echo $kyuubiInfo | cut -d " " -f3` 
 masterNode=`echo $kyuubiInfo | cut -d " " -f4` 
 node=`hostname`

 #是否安装
 if [[ $isInstall = "true" && $kyuubiNodes =~ $node ]];then
    
     #2.查看$PLAY_HOME/frames目录下是否有kyuubi安装包
     kyuubiIsExists=`find $PLAY_HOME/frames -name $kyuubi`

     if [[ ${#kyuubiIsExists} -ne 0 ]];then

          if [[ ! -d /opt/app ]];then
              mkdir /opt/app && chmod -R 775 /opt/app
          fi

          #删除旧的
          kyuubi_home_old=`find /opt/app -maxdepth 1 -name "apache-kyuubi*"`
          for i in $kyuubi_home_old;do
                rm -rf $i
          done

          #3.解压到指定文件夹/opt/app中
          echo "开始解压kyuubi安装包"
          tar -zxvf $kyuubiIsExists -C /opt/app >& /dev/null
          echo "kyuubi安装包解压完毕"

          kyuubi_home=`find /opt/app -maxdepth 1 -name "apache-kyuubi*"`

          #4.配置kyuubi-defaults.conf文件
          if [ -f "$kyuubi_home/conf/kyuubi-defaults.conf.template" ]; then
              cp $kyuubi_home/conf/kyuubi-defaults.conf.template $kyuubi_home/conf/kyuubi-defaults.conf
          fi
          
          configureKyuubiConf $kyuubi_home/conf/kyuubi-defaults.conf $masterNode $node

          #5.配置KYUUBI_HOME
          profile=/etc/profile
          sed -i "/^export KYUUBI_HOME/d" $profile
          echo "export KYUUBI_HOME=$kyuubi_home" >> $profile

          #6.配置PATH
          sed -i "/^export PATH=\$PATH:\$KYUUBI_HOME\/bin/d" $profile
          echo "export PATH=\$PATH:\$KYUUBI_HOME/bin" >> $profile

          #7.更新/etc/profile文件
          source /etc/profile && source /etc/profile
          
          echo "Kyuubi安装完成"
     else
         echo "$PLAY_HOME/frames目录下没有kyuubi安装包"
     fi
 else
     echo "Kyuubi不允许安装在当前节点，请检查配置文件！"
 fi

}

installKyuubi